// 腾讯地图工具类
import { TENCENT_MAP_CONFIG, MARKER_STYLES, LAYER_CONFIG } from '@/config/tencent-map.js'

export class MapUtils {
  constructor() {
    this.map = null
    this.markers = []
    this.layers = {}
  }

  // 初始化地图
  initMap(containerId, options = {}) {
    const config = {
      ...TENCENT_MAP_CONFIG,
      ...options
    }
    
    return new Promise((resolve, reject) => {
      // #ifdef H5
      // H5 环境 - 跳过地图初始化，避免 Key 配置错误
      console.log('H5 环境：跳过地图初始化')
      resolve(null)
      // #endif
      
      // #ifdef MP-WEIXIN
      // 微信小程序环境 - 使用腾讯地图 GL JS API
      if (typeof TMap === 'undefined') {
        const script = document.createElement('script')
        script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${config.key}&callback=initTencentMap`
        script.onerror = reject
        document.head.appendChild(script)
        
        window.initTencentMap = () => {
          this.map = new TMap.Map(containerId, {
            center: new TMap.LatLng(config.center[1], config.center[0]),
            zoom: config.zoom
          })
          resolve(this.map)
        }
      } else {
        this.map = new TMap.Map(containerId, {
          center: new TMap.LatLng(config.center[1], config.center[0]),
          zoom: config.zoom
        })
        resolve(this.map)
      }
      // #endif
    })
  }

  // 添加设备标记
  addDeviceMarker(deviceInfo) {
    const marker = new TMap.MultiMarker({
      map: this.map,
      styles: {
        default: new TMap.MarkerStyle({
          width: 20,
          height: 20,
          anchor: { x: 10, y: 10 },
          src: this.getMarkerIcon(deviceInfo.status)
        })
      },
      geometries: [{
        id: deviceInfo.id,
        position: new TMap.LatLng(deviceInfo.latitude, deviceInfo.longitude),
        properties: {
          title: deviceInfo.deviceName,
          ...deviceInfo
        }
      }]
    })
    
    // 添加点击事件
    marker.on('click', (e) => {
      this.showDeviceInfo(e.geometry.properties)
    })
    
    this.markers.push(marker)
    return marker
  }

  // 添加污染源标记
  addPollutionMarker(factoryInfo) {
    const marker = new TMap.MultiMarker({
      map: this.map,
      styles: {
        pollution: new TMap.MarkerStyle({
          width: 20,
          height: 20,
          anchor: { x: 10, y: 10 },
          src: MARKER_STYLES.pollution.icon
        })
      },
      geometries: [{
        id: factoryInfo.id,
        position: new TMap.LatLng(factoryInfo.latitude, factoryInfo.longitude),
        properties: {
          title: factoryInfo.factoryName,
          ...factoryInfo
        }
      }]
    })
    
    marker.on('click', (e) => {
      this.showFactoryInfo(e.geometry.properties)
    })
    
    this.markers.push(marker)
    return marker
  }

  // 根据设备状态获取标记图标
  getMarkerIcon(status) {
    switch (status) {
      case 1: // 在线
        return MARKER_STYLES.normal.icon
      case 2: // 离线
        return MARKER_STYLES.offline.icon
      case 3: // 故障
        return MARKER_STYLES.abnormal.icon
      default:
        return MARKER_STYLES.normal.icon
    }
  }

  // 显示设备信息
  showDeviceInfo(deviceInfo) {
    const infoWindow = new TMap.InfoWindow({
      map: this.map,
      position: new TMap.LatLng(deviceInfo.latitude, deviceInfo.longitude),
      content: this.createDeviceInfoContent(deviceInfo),
      offset: { x: 0, y: -30 }
    })
    
    infoWindow.open()
  }

  // 显示工厂信息
  showFactoryInfo(factoryInfo) {
    const infoWindow = new TMap.InfoWindow({
      map: this.map,
      position: new TMap.LatLng(factoryInfo.latitude, factoryInfo.longitude),
      content: this.createFactoryInfoContent(factoryInfo),
      offset: { x: 0, y: -30 }
    })
    
    infoWindow.open()
  }

  // 创建设备信息内容
  createDeviceInfoContent(deviceInfo) {
    const statusText = this.getDeviceStatusText(deviceInfo.status)
    const statusColor = this.getDeviceStatusColor(deviceInfo.status)
    
    return `
      <div style="padding: 10px; min-width: 200px;">
        <h4 style="margin: 0 0 8px 0; color: #333;">${deviceInfo.deviceName}</h4>
        <p style="margin: 4px 0; color: #666;">设备编码: ${deviceInfo.deviceCode}</p>
        <p style="margin: 4px 0; color: #666;">设备类型: ${deviceInfo.deviceType}</p>
        <p style="margin: 4px 0; color: #666;">安装位置: ${deviceInfo.installLocation}</p>
        <p style="margin: 4px 0;">
          状态: <span style="color: ${statusColor}; font-weight: bold;">${statusText}</span>
        </p>
        <p style="margin: 4px 0; color: #666;">负责人: ${deviceInfo.responsiblePerson}</p>
        <p style="margin: 4px 0; color: #666;">联系电话: ${deviceInfo.contactPhone}</p>
      </div>
    `
  }

  // 创建工厂信息内容
  createFactoryInfoContent(factoryInfo) {
    const riskText = this.getRiskLevelText(factoryInfo.riskLevel)
    const riskColor = this.getRiskLevelColor(factoryInfo.riskLevel)
    
    return `
      <div style="padding: 10px; min-width: 200px;">
        <h4 style="margin: 0 0 8px 0; color: #333;">${factoryInfo.factoryName}</h4>
        <p style="margin: 4px 0; color: #666;">工厂编码: ${factoryInfo.factoryCode}</p>
        <p style="margin: 4px 0; color: #666;">工厂类型: ${factoryInfo.factoryType}</p>
        <p style="margin: 4px 0; color: #666;">地址: ${factoryInfo.address}</p>
        <p style="margin: 4px 0; color: #666;">主要污染物: ${factoryInfo.mainPollutants}</p>
        <p style="margin: 4px 0;">
          风险等级: <span style="color: ${riskColor}; font-weight: bold;">${riskText}</span>
        </p>
      </div>
    `
  }

  // 获取设备状态文本
  getDeviceStatusText(status) {
    const statusMap = {
      1: '在线',
      2: '离线',
      3: '故障'
    }
    return statusMap[status] || '未知'
  }

  // 获取设备状态颜色
  getDeviceStatusColor(status) {
    const colorMap = {
      1: '#4cd964', // 绿色 - 在线
      2: '#999999', // 灰色 - 离线
      3: '#dd524d'  // 红色 - 故障
    }
    return colorMap[status] || '#999999'
  }

  // 获取风险等级文本
  getRiskLevelText(riskLevel) {
    const riskMap = {
      1: '低风险',
      2: '中风险',
      3: '高风险'
    }
    return riskMap[riskLevel] || '未知'
  }

  // 获取风险等级颜色
  getRiskLevelColor(riskLevel) {
    const colorMap = {
      1: '#4cd964', // 绿色 - 低风险
      2: '#f0ad4e', // 橙色 - 中风险
      3: '#dd524d'  // 红色 - 高风险
    }
    return colorMap[riskLevel] || '#999999'
  }

  // 清除所有标记
  clearMarkers() {
    this.markers.forEach(marker => {
      marker.setMap(null)
    })
    this.markers = []
  }

  // 销毁地图
  destroy() {
    if (this.map) {
      this.map.destroy()
      this.map = null
    }
  }
}